var oprateUrl=DOMAIN +'/v1/product'+isLogin;
productFlg=true;
$(document).ready(function() {
	loadTable();
	//getSelList($("#units"),"specifications");
	getTypeList($("#units"),"/v1/units");
	getSelList($("#grade"),"grade");
	
	$("#units").on("change",function(){
		if($("#units option:checked").html() == "斤"){
			$("#suttle").val("0.5");
		}else{
			$("#suttle").val("");
		}
	});
	
	//查询
	$("#searchBtn").click(function() {
		//新查询参数
		function queryParamNew(params) {
			var params = {};
			params.code = $("#code").val();
			params.name = $("#name").val();
			//params.specifications = $("#specifications").val();
			return params;
		};
		$('#table').bootstrapTable(
			'refreshOptions', {
				url: oprateUrl,
				//查询参数
				queryParams: queryParamNew
			}
		);

	});
});

function loadTable() {
	$('#table').bootstrapTable({
		url: oprateUrl,
		method: 'get',
		dataType: "json",
		contentType: "application/x-www-form-urlencoded",
		toolbar: '#toolbar',
		striped: true,
		cache: false,
		pagination: true,
		sortable: false,
		sortOrder: "asc",
		showRefresh: false,
		showColumns: false,
		minimumCountColumns: 4,
		search: false,
		queryParams: queryParams,
		toolbar: '#exampleTableEventsToolbar',
		sidePagination: "client",
		pageNumber: 1,
		pageSize: 50,
		pageList: [50,100],
		strictSearch: true,
		clickToSelect: true,
		cardView: false,
		detailView: false,
		columns: [{
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			visible: false
		},{
			field: 'code',
			title: "产品代码",
			align: "center",
			valign: "middle"
		}/*,{
			field: 'gbCode',
			title: "国标码",
			align: "center",
			valign: "middle"
		}*/, {
			field: "name",
			title: "产品名称",
			align: "center",
			valign: "middle"
		},{
			field: "levelOneName",
			title: "所属一级类型名称",
			align: "center",
			valign: "middle",
			visible: false
		},{
			field: "levelOneId",
			title: "所属一级类型id",
			align: "center",
			valign: "middle",
			visible: false
		},{
			field: "levelTwoName",
			title: "所属二级类型名称",
			align: "center",
			valign: "middle",
			visible: false
		},{
			field: "levelTwoId",
			title: "所属二级类型id",
			align: "center",
			valign: "middle",
			visible: false
		},{
			field: 'type',
			title: "类别",
			align: "center",
			valign: "middle",
            formatter: function (value, row, index) {
                return row.levelOneName + "/" + row.levelTwoName;
            }
		},{
			field: "gradeName",
			title: "产品等级",
			align: "center",
			valign: "middle"
		},{
			field: "grade",
			title: "等级代码",
			align: "center",
			valign: "middle",
			visible: false
		}/*,{
			field: "specifications",
			title: "规格",
			align: "center",
			valign: "middle"
		}*/,{
			field: "units",
			title: "单位",
			align: "center",
			valign: "middle"
		},{
			field: "suttle",
			title: "净重（公斤）",
			align: "center",
			valign: "middle"
		}/*,{
			field: "divisionName",
			title: "产地",
			align: "center",
			valign: "middle"
		},{
			field: "division",
			title: "产地代码",
			align: "center",
			valign: "middle",
			visible: false
		}*/, {
			field: "",
			title: "操作",
			align: "center",
			valign: "middle",
			events: funOprate,
			formatter: function(value,row,index) { 
				return '<button data-toggle="modal" data-edit="div-modal" data-target="#div-modal" class="btn btn-primary btn-sm edit" onclick="showBox();">&emsp;编辑</button> <button data-del="'+oprateUrl+'" class="btn btn-primary btn-sm del">&emsp;删除</button>';
	        } 
		}],
		onLoadSuccess: function() {
			console.log("加载成功");
		},
		onLoadError: function() {
			console.log("加载数据失败");
		},
		//>>>>>>>>>>>>>>导出excel表格设置
		showExport: true,
		  //是否显示导出按钮
		    buttonsAlign: "left",
		  //按钮位置
		    exportDataType: 'all',
		   //导出的方式 all全部 selected已选择的  basic', 'all', 'selected'.
		    Icons: 'glyphicon glyphicon-export',
		    exportTypes: ['excel', 'doc', 'xlsx', 'txt', ],
		  //导出文件类型
		    exportOptions: {       //ignoreColumn: [0,1],  //忽略某一列的索引
			      
			fileName: '导出数据表',
			  //文件名称设置
			      worksheetName: 'sheet1',
			  //表格工作区名称
			      tableName: '导出数据表',
			       // excelstyles: ['background-color', 'color', 'font-size', 'font-weight'], 设置格式
			    
		},
		//导出excel表格设置<<<<<<<<<<<<<<<<
	});
	//查询参数
	function queryParams(params) {
		var params = {};
		return params;
	};
};

//保存
function funSave(){
    var id = $("#id").val();
	var type ="";
	var data = $("#form-modal").serialize();
    if(isNotEmpty(id)){//修改
    	type="PATCH";
    }else{//新增
    	type="POST";
    }
    $.ajax({
        type : type,
        url : oprateUrl,
        data:data,
        async: false,  
        success : function(result) {
        	if (result.status == 200) {
        		$('.close').click();
        		document.getElementById("form-modal").reset();
    			$("#id").val("");
    			alert("操作成功");
	        	$("#table").bootstrapTable("refresh", {
			     silent: true //静态刷新
			    });
			}
        	if (result.status == 402) {
        		alert(result.msg);
			}
        },
        error : function() {
        	alert("修改失败！");
        }
    });
};
//保存
$("#btn-save").click(function() {
	if(isEmpty($("#pname").val())||isEmpty($("#units").val())||isEmpty($("#levelOneName").val())||isEmpty($("#levelTwoName").val())||isEmpty($("#grade option:checked").val())){
		alert("请填写完整信息!");
		return;
	}
	if(isEmpty($("#suttle").val())||$("#suttle").val()<=0){
		alert("产品净重必须大于0!");
		return;
	}
	funSave();
});

//关闭
$("#btn-close").click(function() {
    document.getElementById("form-modal").reset();
    $("#id").val("");
});

$("#Btn-insert").click(function() {
	 $("#id").val("");
     $("#form-modal")[0].reset();
     $("#codeBox").css("display","none");
     $("#modalTitle").text("新增");
     $("#suttle").val("0.5");
});

function showBox(){
     $("#codeBox").css("display","block");
     $("#modalTitle").text("修改");
}

function selectLevelOne(row){
	$("#levelOneName").val(row.name);
	$("#levelOneId").val(row.id);
	$("#levelTwoName").val("");
	$("#levelTwoId").val("");
}

function selectLevelTwo(row){
	$("#levelTwoName").val(row.name);
	$("#levelTwoId").val(row.id);
}

function selectDivision(row){
	$("#divisionName").val(row.name);
	$("#division").val(row.code);
}



var times2 =0;
function getTypeList(ele, selUrl){
	var url = DOMAIN + selUrl+isLogin;
    var proList = '';
    $.ajax({
        type: 'get',
        contentType: 'application/json;charset=utf-8',
        url: url,
        dataType: 'json',

        success: function (res) {
            var data = res.data;
            for (var i = 0; i < data.length; i++) {
                proList += '<option value = ' + data[i].name + '>' + data[i].name + '</option>'
            }
            ele.html(proList);
            times2=0;
        },
        error: function(jqXHR, textStatus, errorThrown){
        	if(jqXHR.status=="401" && times2<=3){
        		times2++;
        		getSelList(ele, dataType);
        	}else{
        		times2 = 0;
        	}
        }

    });
}